/* eslint-disable no-undef */
// import { wxsdk } from '@/api/wxsdk'
// import Fingerprint2 from 'fingerprintjs2'

// export function fingerprintjs() {
//   const excludes = {}
//   excludes.userAgent = true
//   excludes.audio = true
//   excludes.enumerateDevices = true
//   excludes.fonts = true
//   excludes.fontsFlash = true
//   excludes.webgl = true
//   excludes.canvas = true
//   const options = { excludes: excludes }
//   let Fingerprint
//   Fingerprint2.get(options, function(components) {
//     // 参数
//     const values = components.map(function(component) {
//       return component.value
//     })
//     // 指纹
//     const murmur = Fingerprint2.x64hash128(values.join(''), 31)
//     Fingerprint = murmur
//   })
//   return Fingerprint
// }

export const disYears = (time = '1991-03') => {
  let dis = 0
  if (!time) {
    console.warn('disYears time is emtpy !!!')
    return dis
  }
  const nowDate = new Date()
  const nowYear = nowDate.getFullYear()

  const timeYear = time.slice(0, 4)
  dis = nowYear - Number.parseInt(timeYear)
  return dis
}
/**
 * [formatSearch 将地址栏参数转换成对象]
 *
 * @return  {[Array]}
 */
export function formatSearch(target) {
  if (isBrowser()) {
    if (!window) {
      console.warn('window is not defined')
      return
    }
    if (target || window.location.search) {
      const param = {}
      const target_search = target || window.location.search
      const search = target_search.split('?')[1]
      const array = search.split('&')
      array.forEach(item => {
        const arr = item.split('=')
        param[arr[0]] = arr[1]
      })
      return param
    }
    return {}
  }
}

export function isBrowser() {
  if (!process) {
    console.warn('process is not defined')
    return false
  }
  if (process.browser) {
    return true
  } else {
    return false
  }
}

export function isServer() {
  if (!process) {
    console.warn('process is not defined')
    return false
  }
  if (process.server) {
    return true
  } else {
    return false
  }
}

export function getElementToPageTop(el) {
  if (el.parentElement) {
    return getElementToPageTop(el.parentElement) + el.offsetTop
  }
  return el.offsetTop
}

// 格式化文章时间
export function times(str) {
  var str1 = str.replace(/-/g, '-')
  var str2 = str1.slice(str1.indexOf('-') + 1, str1.lastIndexOf(':'))
  return str2
}

// 拿到图片的高度
export function getImageHeight({ imgUri, width = 750 }) {
  let imageHeight = 0
  if (!imgUri) {
    return imageHeight
  }
  const index2 = imgUri.indexOf('?')
  let styleStr
  if (index2 < 0) {
    return imageHeight
  } else {
    styleStr = imgUri.substring(index2 + 1)
  }

  const styles = {}
  styleStr &&
    styleStr.split('&').map(str => {
      const index3 = str.indexOf('=')
      const arr0 = str.substring(0, index3)
      const arr1 = str.substring(index3 + 1)
      styles[arr0] = arr1
    })

  const imgWidth = styles.width
  const imgHeight = styles.height

  if (imgWidth && imgHeight) {
    imageHeight = (width / imgWidth) * imgHeight
  }

  return imageHeight
}

export function filterQuery(params) {
  if (typeof params !== 'object') {
    console.log('params is not a object')
    return false
  }
  const keys = Object.keys(params)
  const newParam = {}
  keys.forEach(item => {
    if (item === 'register_channel' || item === '_channel') {
      newParam[item] = params[item]
    }
  })
  return newParam
}

// 处理后台传过来的标签图片太大
export function imgnode(el, answer) {
  if (answer) {
    let pImg = []
    document.querySelectorAll(el).forEach(item => {
      if (Array.prototype.slice.call(item.getElementsByTagName('img')).length) {
        pImg = [...pImg, ...Array.prototype.slice.call(item.getElementsByTagName('img'))]
      }
    })
    pImg.forEach(item => {
      item.style.maxWidth = 100 + '%'
      if (item.children.length > 0) {
        item.children[0].style.width = 100 + '%'
      }
    })
  } else {
    if (document.querySelector(el) != null) {
      const pImg = [...document.querySelector(el).getElementsByTagName('img')]
      pImg.forEach(item => {
        item.style.maxWidth = 100 + '%'
        item.style.display = 'flex'
        item.style.margin = '0 auto'
        if (item.children.length > 0) {
          item.children[0].style.width = 100 + '%'
        }
      })
    }
  }
}
// wxSDK处理
// export function initShare(title, desc, link, imgUrl, deviceType) {
//   if (deviceType.env === 'wechat') {
//     if (isBrowser()) {
//       const _url = encodeURIComponent(window.location.href)
//       wxsdk(_url).then(res => {
//         // eslint-disable-next-line no-undef
//         wx.config({
//           debug: false,
//           appId: res.data.appId,
//           timestamp: res.data.timestamp,
//           nonceStr: res.data.nonceStr,
//           signature: res.data.signature,
//           jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
//         })
//         wx.ready(function() {
//           wx.updateAppMessageShareData({
//             title: title,
//             desc: desc,
//             link: link,
//             imgUrl: imgUrl,
//             success: function() { }
//           })
//         })
//         wx.ready(function() {
//           wx.updateTimelineShareData({
//             title: title,
//             link: link,
//             imgUrl: imgUrl,
//             success: function() {
//               // 设置成功
//             }
//           })
//         })
//       })
//     }
//   }
// }
/**
 * [formateTime 后端时间格式为  1999-12-31 12:31:43]
 *
 * @return  {[String]}  [return 1999/12/31 12:31:43]
 */
export function formataTime(time = '1999-12-31 12:31:43') {
  time = time.replace(/-/g, '/')
  return time
}

// 获取滚动条当前的位置
export function getScrollTop() {
  var scrollTop = 0
  if (document.documentElement && document.documentElement.scrollTop) {
    scrollTop = document.documentElement.scrollTop
  } else if (document.body) {
    scrollTop = document.body.scrollTop
  }
  return scrollTop
}

// 获取当前可视范围的高度
export function getClientHeight() {
  var clientHeight = 0
  if (document.body.clientHeight && document.documentElement.clientHeight) {
    clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight)
  } else {
    clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight)
  }
  return clientHeight
}

// 获取文档完整的高度
export function getScrollHeight() {
  // var height = 0
  // if (document.compatMode === 'BackCompat') {
  //   height = document.body.scrollHeight
  // } else {
  //   height = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight)
  // }
  // return height
  var xScroll, yScroll
  if (window.innerHeight && window.scrollMaxY) {
    xScroll = window.innerWidth + window.scrollMaxX
    yScroll = window.innerHeight + window.scrollMaxY
  } else {
    if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
      xScroll = document.body.scrollWidth
      yScroll = document.body.scrollHeight
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      xScroll = document.body.offsetWidth
      yScroll = document.body.offsetHeight
    }
  }
  // eslint-disable-next-line no-unused-vars
  var windowWidth, windowHeight, pageHeight, pageWidth
  if (self.innerHeight) { // all except Explorer
    if (document.documentElement.clientWidth) {
      windowWidth = document.documentElement.clientWidth
    } else {
      windowWidth = self.innerWidth
    }
    windowHeight = self.innerHeight
  } else {
    if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowWidth = document.documentElement.clientWidth
      windowHeight = document.documentElement.clientHeight
    } else {
      if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth
        windowHeight = document.body.clientHeight
      }
    }
  }
  // for small pages with total height less then height of the viewport
  if (yScroll < windowHeight) {
    pageHeight = windowHeight
  } else {
    pageHeight = yScroll
  }
  // for small pages with total width less then width of the viewport
  if (xScroll < windowWidth) {
    pageWidth = xScroll
  } else {
    pageWidth = windowWidth
  }
  var arrayPageSize = [windowWidth, windowHeight, pageHeight, pageWidth]
  return arrayPageSize
}

export function MP(ak) {
  return new Promise(function(resolve, reject) {
    window.onload = function() {
      resolve(BMap)
    }
    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = '//api.map.baidu.com/api?v=2.0&ak=' + ak + '&callback=init'
    script.onerror = reject
    document.head.appendChild(script)
  })
}
// 节流
export function throttle(fn, interval = 300) {
  let canRun = true
  return function() {
    if (!canRun) return
    canRun = false
    setTimeout(() => {
      fn.apply(this, arguments)
      canRun = true
    }, interval)
  }
}
// 防抖
export function debounce(func, wait = 500, immediate = false) {
  let timeout
  return function() {
    const context = this
    const args = arguments

    if (timeout) clearTimeout(timeout)
    if (immediate) {
      var callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function() {
        func.apply(context, args)
      }, wait)
    }
  }
}

// 获取url地址query参数
export function getQueryVariable(variable) {
  var query = window.location.search.substring(1)
  var vars = query.split('&')
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=')
    if (pair[0] === variable) { return pair[1] }
  }
  return (false)
}
